import { PickerItemData } from '../panel/Picker/config';

export function parseJSON(json?: string) {
    try {
        return json ? JSON.parse(json) : null;
    } catch (error) {
        return null;
    }
}

let i = 0;

export const uniqueKey = () => `${i++}`;

type Handler<T = any> = (data: T, ...args: any[]) => void;

export class EventEmitter<P> {
    pool: Record<string, Handler[]> = {};

    on = (name: string, handler: Handler<P>) => {
        (this.pool[name] || (this.pool[name] = [])).push(handler);
    };

    emit = <T = P>(name: string, data: T, ...args: any[]) => {
        this.pool[name]?.forEach(fn => fn(data, ...args));
    };

    unlisten = (name: string, handler: Handler<P>) => {
        const foundIndex = this.pool[name]?.findIndex(h => h === handler);

        if (foundIndex !== -1) {
            this.pool[name]?.splice(foundIndex, 1);
        }
    };
}

export const eventBus = new EventEmitter<any>();
